package com.funo.oeip.regcenter.zkcli;


import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * 权限控制演示
 * @author simonfj
 *
 */
public class AclCreateWatcher implements Watcher {
	private static final String CONNECTION_IP = "localhost:2181";
	private static final String ZNODE_NAME = "/node01";
	private static final String ZNODE_VALUE = "node01-value";

	private static CountDownLatch latch = new CountDownLatch(1);

	private static ZooKeeper zk = null;

	public void syncInit() {
		try {
			zk = new ZooKeeper(CONNECTION_IP, 5000, new AclCreateWatcher());
			latch.await();
			zk.addAuthInfo("digest", "user1:12345".getBytes());
			Stat stat = zk.exists(ZNODE_NAME, false);
			if ( null == stat) {
				zk.create(ZNODE_NAME, ZNODE_VALUE.getBytes(), Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
			}
			String value1 = new String(zk.getData(ZNODE_NAME, false, null));
			System.out.println("zk有权限进行数据的获取:" + value1);

			ZooKeeper zk3 = new ZooKeeper(CONNECTION_IP, 5000, null);
			zk3.addAuthInfo("digest", "user2:12345".getBytes());
			String value2 = new String(zk3.getData(ZNODE_NAME, false, null));
			System.out.println("zk3有权限进行数据的获取" + value2);

			// ZooKeeper zk2 = new ZooKeeper(CONNECTION_IP, 5000, null);
			// zk2.addAuthInfo("digest", "super:123".getBytes());
			// zk2.getData(ZNODE_NAME, false, null);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (KeeperException e) {
			System.out.println("异常:" + e.getMessage());
		}
	}

	public void process(WatchedEvent event) {
		if (KeeperState.SyncConnected == event.getState()) {
			if (event.getType() == EventType.None && null == event.getPath()) {
				latch.countDown();
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		AclCreateWatcher acl_Create = new AclCreateWatcher();
		acl_Create.syncInit();
	}

}